package array;

import java.util.ArrayList;
import java.util.Arrays;

//合并区间
public class leetcode56 {
    public static void main(String[] args){
        int[][] intervals = {{1,3},{2,6},{8,10},{15,18}};
        int[][] results = merge(intervals);
        printArray(results);

    }

    //数组保存的是地址
    public static int[][] merge(int[][] intervals) {
        if(intervals.length <= 1) return intervals;

        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        ArrayList<int[]> arrayList = new ArrayList<>();
        arrayList.add(0, intervals[0]);
        int[] current = intervals[0];
        for (int[] interval: intervals){

            if(interval[0] <= current[1]){
                current[1] = Math.max(current[1], interval[1]);
            }
            else{
                current = interval;
                arrayList.add(current);
            }
        }

        return arrayList.toArray(new int[arrayList.size()][]);
    }

    public static void printArray(int[][] results){
        for (int i = 0; i < results.length; i++) {
            for (int j = 0; j < results[i].length; j++) {
                System.out.print(results[i][j] + "\t");
            }
            System.out.println();
        }
    }

}
